package com.sosee.cgfw.friends;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.sosee.cgfw.R;
import com.sosee.cgfw.activityname.CaptureActivity;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.Utils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thinkpad on 2016/3/1.
 */
public class FriendsLists extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private RelativeLayout friends_addnew;
    private ListView friends_list;
    private HttpUtils httpUtils;
    List<FriendsListData.Data> data;
    private ImageButton friends_back6;
    private  ImageButton friends_saomiao1;
    private static final int PHOTO_PIC = 1;

    private RelativeLayout rl_search1;

    String[] letter={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"};

    String[] cityLetter={};

    String[] cityName={};
    List<String> letterToCity=new ArrayList<String>();
    private Map<String,String> map=new HashMap<String, String>();//根据名称 获取好友id
    private Map<String,String> map1=new HashMap<String, String>();//根据名称 获取好友备注
    private String userName;//选中的 好友名称
    ListView lv;
    ListView lv1;
    String userID;
    private String name;
    String marks;
//    List<String> friendsId = new ArrayList<String>();

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friendslists);
        httpUtils=new HttpUtils();

        init();

    }

    private void init() {
        friends_addnew = (RelativeLayout) findViewById(R.id.friends_addnew);
        friends_list= (ListView)findViewById(R.id.friends_list);
        friends_list.setAdapter(new MyFriendsAdapter());
        rl_search1 = (RelativeLayout)findViewById(R.id.rl_search1);
        friends_saomiao1= (ImageButton)findViewById(R.id.friends_saomiao1);


        friends_back6 = (ImageButton)findViewById(R.id.friends_back6);
        friends_addnew.setOnClickListener(this);
        friends_back6.setOnClickListener(this);
        rl_search1.setOnClickListener(this);
        friends_saomiao1.setOnClickListener(this);

        requestHttp();
    }

    private void requestHttp() {
        httpUtils.configCurrentHttpCacheExpiry(100);
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.GETFRIENDSLIST_URL+Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                SharedPreferencesUtils.putString(FriendsLists.this,"dd",result);
                System.out.println("我是好友列表返回的数据：" + result);

                Gson gson = new Gson();
                FriendsListData friendsListData = gson.fromJson(result, FriendsListData.class);
                data = friendsListData.getData();


                if("success".equals(friendsListData.getStatus())){
                    map.clear();
                    map1.clear();

                    cityLetter = new String[data.size()];
                    cityName = new String[data.size()];

                    for (int i = 0; i < data.size(); i++) {

                        //这里设置判断，
                        if(null==data.get(i).getRemarks()||"".equals(data.get(i).getRemarks())||"-".equals(data.get(i).getRemarks())){

                            name = data.get(i).getFriends().getNickname();

                        }else {
                            name = data.get(i).getRemarks();

                        }

                        if("1".equals(data.get(i).getFlag())){
                        Constans.friendsId=new ArrayList<String>();
                        Constans.friendsId.add(data.get(i).getFriends().getID());

                        //吧首字母赋值给nameletter。
                        String reg = "[a-zA-Z]";
                        String str = Utils.getPinYinHeadChar(name);

                        boolean isCract = str.matches(reg);
                        if(isCract){
                            cityLetter[i] = Utils.getPinYinHeadChar(name);
                        }else{
                            cityLetter[i] = "#";
                        }
                        //吧名字赋值给name
                        cityName[i] = name;

                        //吧名称和ID存起来
                        map.put(name, data.get(i).getFriends().getID());
                        map1.put(name,data.get(i).getRemarks());
                        }
                    }


                }else{


                }


                initView();

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });    }

    public void initView(){

        letterToCity.clear();
        String str="";
        for(int i=0;i<letter.length;i++){
            //a
            str=letter[i];
            //是否添加
            boolean isAddLetter=false;
            //循环到 c
            for(int j=0;j<cityLetter.length;j++){
                //如果 s= 名称首字母s
                if(str.equals(cityLetter[j])){
                    if(!isAddLetter){
                        //酒吧s添加到集合中去

                        letterToCity.add(str);
                        isAddLetter=true;
                    }
                    //不然就添加名称
                    letterToCity.add(cityName[j]);
                }

            }
        }

        lv=(ListView)findViewById(R.id.friends_list);
        lv.setAdapter(new MyFriendsAdapter());
        lv.setOnItemClickListener(this);

        lv1=(ListView)findViewById(R.id.friends_listlellter);
        lv1.setAdapter(new MyAdapter1());
        //设置listview的条目和另外的对应。
        lv1.setOnItemClickListener(this);

    }



    //这是显示旁边abc的右导航边框。
    class MyAdapter1 extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return letter.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return letter[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view= LayoutInflater.from(FriendsLists.this).inflate(R.layout.letter_list, null);
            TextView tv=(TextView)view.findViewById(R.id.letterListTextView);
            tv.setText(letter[position]);
            return view;
        }

    }

    public class MyFriendsAdapter extends BaseAdapter{

        final static int TYPE_1=1;
        final static int TYPE_2=2;
        @Override
        public int getCount() {
            return letterToCity.size();
        }

        @Override
        public Object getItem(int position) {
            return letterToCity.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            //这是返回类型，如果获取到的首字母=leter，就返回类型1，否则就返回类型2，但是
            int count=0;
            for(int i=0;i<letter.length;i++){
                if(letter[i].equals(letterToCity.get(position))){

                    //这里能判断让他类型
                    return TYPE_1;

                }
            }
            return TYPE_2;
        }

        @Override
        public int getViewTypeCount() {
            return 3;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

                /**
                 * 即使convertView缓存了一些布局，但是在重构时，根本不知道怎么样去让convertView返回你所需要的布局，这时你需
                 * 要让adapter知道我当前有哪些布局，我重构Item时的布局选取规则，好让convertView能返回你需要的布局。
                 * 需要重写以下两个函数
                 * @Override
                 * public int getItemViewType(int position) {}这个函数获取在getView中创建的视图的类型
                 * @Override
                 * public int getViewTypeCount() {}返回在getView中创建视图类型的数量
                 * 至于这两个方法的详细用处，自己看api即可
                 */
                ViewHolder1 vh1=null;
                ViewHolder2 vh2=null;
                int type=getItemViewType(position);
                if(convertView==null){
                    switch (type) {
                        case TYPE_1:
                            convertView=LayoutInflater.from(FriendsLists.this).inflate(R.layout.letter, null);
                            vh1=new ViewHolder1();
                            vh1.tv=(TextView)convertView.findViewById(R.id.letterTextView);
                            convertView.setTag(vh1);
                            break;
                        case TYPE_2:
                            convertView=LayoutInflater.from(FriendsLists.this).inflate(R.layout.friends_myfriends_item, null);
                            vh2=new ViewHolder2();
                            vh2.friends_friendsname=(TextView)convertView.findViewById(R.id.friends_friendsname);
                            convertView.setTag(vh2);
                            break;
                        default:
                            break;
                    }
                }else{
                    switch (type) {
                        case TYPE_1:
                            vh1=(ViewHolder1)convertView.getTag();
                            break;
                        case TYPE_2:
                            vh2=(ViewHolder2)convertView.getTag();
                            break;
                        default:
                            break;
                    }
                }
                //这里就是设置每个条目需要显示的值。
                switch (type) {
                    case TYPE_1:

                            String reg = "[a-zA-Z]";
                            String str = letterToCity.get(position);
                            boolean isCract = str.matches(reg);
                                if(null==letterToCity.get(position)||"".equals(letterToCity.get(position))||!isCract){

                                    vh1.tv.setText("#");
                                    vh1.tv.setTextColor(Color.WHITE);

                                     }
                                else {
                                    vh1.tv.setText(letterToCity.get(position));
                                    vh1.tv.setTextColor(Color.WHITE);

                                }

                        break;
                    case TYPE_2:

                        vh2.friends_friendsname.setText(letterToCity.get(position));
                        break;
                    default:
                        break;
                }
                return convertView;

        }
    }

    class ViewHolder1{
        TextView tv;
    }
    class ViewHolder2{
        TextView friends_friendsname;
    }

    public void onClick(View v) {

        switch (v.getId()) {
            //新添加好友
            case R.id.friends_addnew:
                startActivity(new Intent(this, FriendsAddNew.class));
                break;
            //搜索好友
            case R.id.rl_search1:
                startActivity(new Intent(this, FriendsSearchLocal.class));
                break;
            case R.id.friends_back6:
               finish();
                break;
            //扫描添加好友
            case R.id.friends_saomiao1:
                Intent intent3 = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent3, PHOTO_PIC);
//                startActivity(new Intent(this, FriendsScann.class));
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        switch (parent.getId()) {
            case R.id.friends_list:

                boolean  isLetter=false;
                for(int i=0;i<letter.length;i++){
                    if(letter[i].equals(letterToCity.get(position))){
                        isLetter=true;
                        break;
                    }
                }
                if(!isLetter){
                    //获取当前选中好友的名称。
                    userName=parent.getItemAtPosition(position).toString();
//                    Utils.showToast("ID:"+userName);
                    //根据当前好友名称获取对应Id。
                    userID=map.get(userName);
                    marks= map1.get(userName);
//                    Utils.showToast("ID:"+userID);

                    //打开个人信息窗口，然后点击下面的发送按钮的话会跳转到发送消息页面
                    Intent intent = new Intent(FriendsLists.this,FriendsInfo.class);
                    //这里需要把remarks传递过去。
                    intent.putExtra("mark",marks);
                    //吧点击条目的id获取到传递进下一个页面。
                    intent.putExtra("Id",userID);

                    startActivity(intent);
//                    finish();
                }



                break;
            case R.id.friends_listlellter:
                for(int i=0;i<letterToCity.size();i++){
                    if(letter[position].equals(letterToCity.get(i))){
                        lv.setSelection(i);
                        break;
                    }
                }
                break;
            default:
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        imgPath = null;
        if(resultCode == RESULT_OK){
            switch (requestCode) {
//                case CHOOSE_PIC:
//
//                    break;
                case PHOTO_PIC:
                    String result = data.getExtras().getString("result");
//                    Toast.makeText(FriendsLists.this, "结果:" + result, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(FriendsLists.this,FriendsScanResult.class);
                    intent.putExtra("togethers", result);
                    startActivity(intent);
                    finish();
                    break;

                default:
                    break;
            }
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        init();
    }
}

